import type { StoreDefinition } from "pinia";

// 导入所有 core 文件夹下的 .ts 文件
const coreStores = import.meta.glob("./core/*.ts", { eager: true });

// 定义一个数组，用于存储所有的 store 对象
const storeList: { [key: string]: StoreDefinition }[] = [];

const importStore = (stores: Record<string, unknown>) => {
    for (const path in stores) {
        // 获取当前属性对应的值，即模块对象
        const module = stores[path] as { default: StoreDefinition };

        // 获取模块对象的 default 属性，即 StoreDefinition 类型的 store 对象
        const store = module.default;

        // 将 store 对象添加到 storeList 数组中
        storeList.push({
            [store.$id]: store,
        });
    }
};

importStore(coreStores);

/**
 * 重置所有的 store
 */
export const resetStores = () => {
    storeList.forEach((store) => {
        for (const key in store) {
            // 调用每个 store 的 $reset 方法，重置状态
            store[key]().$reset();
        }
    });
};

export const getStore = (storeName: "user" | "room" | "reservation") => {
    const store = storeList.find((store) => store[storeName]);
    if (store) {
        return store[storeName]();
    }
    throw new Error(`Store ${storeName} not found`);
};

// 根据用户角色，动态导入对应的 store
export const asyncImportStore = async (
    role: "admin" | "staff" | "customer"
) => {
    let asyncStores: Record<string, unknown>;
    switch (role) {
        case "admin":
            asyncStores = import.meta.glob("./modules/admin/*.ts", {
                eager: true,
            });
            break;
        case "staff":
            asyncStores = import.meta.glob("./modules/staff/*.ts", {
                eager: true,
            });
            break;
        case "customer":
            asyncStores = import.meta.glob("./modules/customer/*.ts", {
                eager: true,
            });
            break;
    }
    importStore(asyncStores);
};
